<?php
class LocationsController extends AppController {

	var $name = 'Locations';

	function index() {
		$this->Location->recursive = 0;
		$this->set('locations', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid location', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('location', $this->Location->read(null, $id));
	}

	function add($id = null) {
		if (!empty($this->data)) {
			$this->Location->set($this->data);
			
			if($this->Location->validates()) {
			
			$this->Location->create();
			$this->data['Location']['active'] = 1;
			$this->data['Location']['date'] = date("Y-m-d", strtotime($this->data['Location']['date']));}
			else {
				$errors = $this->Location->invalidFields();
			}
			if ($this->Location->save($this->data)) {
				//deactivateother location
				$this->__deactivateLocation($this->data['Location']['item_id'], $this->Location->getLastInsertId());
				$this->Session->setFlash(__('The location has been saved', true));
				$this->redirect(array('controller'=>'items','action' => 'view',$this->data['Location']['item_id']));
			} else {
				$this->Session->setFlash(__('The location could not be saved. Please, try again.', true));
			}
		}
		
		$items = $this->Location->Item->find('list');
		$districts = $this->Location->District->find('list');
		$this->set(compact('items', 'districts','id'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid location', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Location->save($this->data)) {
				$this->Session->setFlash(__('The location has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The location could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Location->read(null, $id);
		}
		$items = $this->Location->Item->find('list');
		$districts = $this->Location->District->find('list');
		$this->set(compact('items', 'districts'));
	}

	function delete($id = null) {
		$this->Location->recursive = -1;
		$item = $this->Location->findById($id);
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for location', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Location->delete($id)) {
			$this->Session->setFlash(__('Location deleted', true));
			$this->redirect(array('controller'=>'items','action'=>'view',$item['Location']['item_id']));
		}
		$this->Session->setFlash(__('Location was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
		
	private function __deactivateLocation($item_id,$activeId) {
		$this->Location->query("UPDATE `asset`.`locations` SET `active`='0' WHERE `item_id`=$item_id AND `id`!=$activeId;");
	}
}
